import cgi

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

import urllib
from google.appengine.api import urlfetch
from google.appengine.ext.webapp import template

import sys,os, httplib,re,string,datetime
from datetime import date

import datastore,library

class Player():
   event = ""
   fname = ""
   lname = ""
   email = ""
   register = ""
   survey = ""

class Event():
   name = ""
   number = ""


class Tournament(db.Model):


 def getEntries(self, tid):
   pass


 def getDelete(self, usta,tid,fname,lname):

   url = "http://www.ustanorcal.com/tournaments/Tournament_Eval_form.asp?"
   arg="UstaNumber="+usta +"&tournamentsSelected="+tid

   result = urlfetch.fetch(url+arg)
   scraped = result.content
#  print scraped

   rsurvey = r"(already completed the evaluation for this tournament)"

   found = re.search( rsurvey, scraped ,re.IGNORECASE)
   if(found!=None):
       return True
   else:
       return False



# ------------------------

class MainPage(webapp.RequestHandler):

  def Writeln(self,t):
    self.response.out.write(t+"\n")

  def Write(self,t):
    self.response.out.write(t)


  def CreateTournamentEntries( self, tid):
     player=[]
     player.append( ("NM3.0s", "922761105","Joel","Brown" , "jbrown@opentable.com"  ) )
     player.append( ("NM3.0s", "2006006484","Corey","Ebadat" , "kcebadat@gmail.com"  ) )
     player.append( ("NM4.5s", "920180951","Gia","Nguyen" , "giatennis@yahoo.com"  ) )
     player.append( ("NM5.0s", "11812432","Shiraz","Madan" , "shiraz@solaradvisorygroup.com"  ) )
     player.append( ("NW4.0d", "921670779","Analiza","Dolor" , "atdolor@yahoo.com"  ) )
     player.append( ("NW4.0d", "922470987","Diana","Nguyen" , "ngdiana2007@gmail.com"  ) )
     player.append( ("NX4.0d", "922531702","Roger","Okamoto" , "rogerusta2003@yahoo.com"  ) )
     player.append( ("NX4.0d", "2008556653","Anh","Vu" , "vu_for_2@yahoo.com"  ) )

     tid="508303511"
     playerlist=[]
     for p in player:
         event = p[0]
         usta = p[1]
         fname = p[2]
         lname = p[3]
         email = p[4]

         key_id = tid + "_" + event +  "_" + usta
         g =  datastore.TournyPlayer.get_or_insert( key_id)
         g.event = event
         g.tournament= tid
         g.usta = usta
         g.email = email
         g.fname = fname
         g.lname = lname
         g.email = email

         if (g.register == None):
            g.register = datetime.datetime.utcnow() - datetime.timedelta(hours = 7)

         playerlist.append(g)

         self.Write(tid +" "+event+", "+fname+" "+lname+" " + email +",<br>")


#   DATASTORE
     db.put( playerlist )


  def get(self):
   pass


class TournyPage(webapp.RequestHandler):

  def Writeln(self,t):
    self.response.out.write(t+"\n")

  def Write(self,t):
    self.response.out.write(t)

  def getEntries(self,tid):
    url = "http://tennislink.usta.com/Tournaments/Reports/ReportPreview.aspx?reportid=1&&tournamentid="+tid
    result = urlfetch.fetch(url)
    scraped = result.content

    page = scraped.split("\r\n")
    rusta  = r' valign="top">([\d]*)<\/td>'           # USTA
    rname  = r"([ \d\w'\-\.]*)[ ,]{2,8}([ d\w'\-\.]*)<\/td>"    # Name   
    revent_pre = r'FieldLabel"'
    revent =  r'([NMWXx]{1,3}[\d]{1}\.[\d]{1,3}[sd]|[MWXO]{2}[psd]{2})'        # event

# Adjustment for new format   
#   <td class="FieldLabel" align="left" valign="top">NM3.0 (  ) s</td>
    revent = r'([NMWXx]{1,3}[\d]{1}\.[\d]{1,3})([ \(\)]*)([\w]{1})'  #event

    remail = r'([\d\w\._\-]*)@([\w\d_\.\-]*)'                 # email
    rstrike = r'(class="FieldLabelStrikeThrough")'            # withdrawal
    rdone = r'(Total Players)'                                # done

    usta = last = first =  email = rstrike=""
    event=[]
    nl="<br>"
    playerlist=[]

    if( re.match("/Users/roger",os.getcwd())):
      nl = ""

    plines = len(page)
    ilast=plines
    finished=0
    for i in range(0,plines-1):
       fusta  = re.search( rusta, page[i] ,re.IGNORECASE)
       fname  = re.search( rname, page[i+1] ,re.IGNORECASE)
       fevent_pre = re.search( revent_pre,page[i] ) # ,re.IGNORECASE)
       fevent = re.search( revent,page[i] ) # ,re.IGNORECASE)
       femail = re.search( remail,page[i] ,re.IGNORECASE)
#      fstrike = re.search( rstrike,page[i] ,re.IGNORECASE)
       fdone = re.search( rdone,page[i] ,re.IGNORECASE)

       if(fdone):
          print("found ", rdone)
          finished=1

       if( (fusta and fname) or finished):
          if( len(usta)>0):
#             print usta,first,last,event,email,str(len(event))+ "events < -------"             
#         ----------------------------------------------------
#      DATASTORE
              for e in event:
#               primary key is tournament, usta# and event
                key_id = tid + "_" + e +  "_" + usta

                print(e+" " + usta + " "+first+" "+last+" "+email+nl)
                g =  datastore.TournyPlayer.get_or_insert( key_id)

                g.tournament = tid
                g.event = e
                g.usta = usta
                g.fname = first
                g.lname = last
                g.email = email

                if (g.register == None):
                 g.register = datetime.datetime.utcnow() - datetime.timedelta(hours = 7)

                playerlist.append(g)
                ilast=i 
#             Since last player done, break out completely
              if( finished): break
#   ----------------------------------------------------
              usta = last = first =  email = ""
              del event[:]


          usta = fusta.group(1)
          last = fname.group(1)
          first = fname.group(2)             


       if( fevent_pre and fevent):
           event.append(fevent.group(1) + fevent.group(3) )

       if( femail):
          email = femail.group(1)+"@"+femail.group(2)

       if( finished):
           print("DONE")
           break


#      if( fstrike):
#          print("strike")



#   for loop indentation end ---------------------------

#   --------------
#   DATASTORE
    db.put( playerlist )


#
  def Display(self, tid):

    query="select __key__ from TournyPlayer  where tournament='"+ tid + "' order by lname"

# Players in each Draw
    draw={}
    keys =  db.GqlQuery( query)
    total=0 
    for k in keys:
        total+=1
        p = db.get(k)
        if p.event in draw.keys():
            draw[p.event] += 1
        else:
            draw[p.event] = 1

#   sort the levels which are represented by the keys  
    level = sorted( list(draw.keys()) )

    elist = []
    for e in level:
       d = Event()       
       d.name = e
       d.number = draw[e]
       elist.append( d)

# Player listed
    keys =  db.GqlQuery( query)
    plist = []
    for k in keys:
        p = db.get(k)
        player =  Player()
        player.event  = p.event
        player.fname  = p.fname 
        player.lname  = p.lname 
        player.email  = p.email 
        day = str(p.register.day)
        hour = str(p.register.hour)
        if(len(day)<2) : day = "0"+day
        if(len(hour)<2) : hour = "0"+hour
        player.register =  str(p.register.month)+"-"+str(day)+ " "+str(hour)+":"+str(p.register.minute)
        if(p.survey==None):
           player.survey = ""
        else:
           day = str(p.survey.day)
           hour = str(p.survey.hour)
           if(len(day)<2) : day = "0"+day
           if(len(hour)<2) : hour = "0"+hour
           player.survey  = str(p.survey.month)+"-"+str(day)+ " "+str(hour)+":"+str(p.survey.minute)

        plist.append( player )

    template_values = {
              'Players' : plist,
              'Events' : elist,
              'Participants' : len(plist)

    }

    path = os.path.join(os.path.dirname(__file__), 'tourny.html')
    self.response.out.write(template.render(path, template_values))

  def DisplayNote( self, tid ):  

    template_values = {

    }

    path = os.path.join(os.path.dirname(__file__), 'displaynote.html')
    self.response.out.write(template.render(path, template_values))


  def getEmail(self,tid):
    query="select __key__ from TournyPlayer  where tournament='"+ tid + "' order by lname"

    last=""
    self.Write('Name,E-mail,Notes<br>')
    keys =  db.GqlQuery( query)
    for k in keys:
        p = db.get(k)
        if( len(p.email) > 0 and (p.fname+p.lname != last) ):
         self.Write(p.fname+" "+p.lname+", "+p.email+",<br>")
         last = p.fname + p.lname



  def getSurvey( self, tid, start, end ):
    query="select __key__ from TournyPlayer where tournament='"+ tid + "' order by lname"
    rsurvey = r"(already completed the evaluation for this tournament)"

    keys =  db.GqlQuery( query)
    count=0
    nl = "<br>"
    for k in keys:
      count =count + 1
      if(count<start ):        continue
      if(count>end ):          break
      p = db.get(k)                         #finally access db
      if( p.survey != None):  
         print("ANS(skip) " +  p.fname + " " + p.lname + " " + str(p.survey) + nl )
         continue     # already answered survey

      url = "http://www.ustanorcal.com/tournaments/Tournament_Eval_form.asp?UstaNumber="+p.usta +"&tournamentsSelected="+tid
      result = urlfetch.fetch(url)
      scraped = result.content

      found = re.search(rsurvey, scraped ,re.IGNORECASE)

      if( found != None):
           print("YES  " + p.fname + " " + p.lname + nl)
           time = datetime.datetime.utcnow() - datetime.timedelta(hours = 7) # for West Coast United
           p.survey=time
           p.put()
      else:
            print("NO  " + p.fname + " " + p.lname + nl)


  def get(self):
    display =  self.request.get('display') 

    note =  self.request.get('note') 

    get =  self.request.get('get') 
    create =  self.request.get('create') 
    survey =  self.request.get('survey') 
    email =  self.request.get('email') 
    clean =  self.request.get('clean') 

    history =  self.request.get('history') 

    start =  self.request.get('start') 
    end =  self.request.get('end') 
    if(start == ""): start ="20"
    if(end == ""): end ="30"
    
    if( note != ""):
        self.DisplayNote( note )
    elif( display != ""):
        self.Display( display )
    elif( get != ""):    
        self.getEntries(get)    # tid = "500002711"
    elif( survey  != ""):    
        self.getSurvey(survey,int(start), int(end) )    # tid = "500002711"
    elif( email != ""):    
        self.getEmail(email)    # tid = "500002711"
    else:
        self.Display("50002711")    # tid = "500002711"

    return



application = webapp.WSGIApplication(
                                     [('/tournament', MainPage),
                                      ('/tourny', TournyPage),
                                      ('/*.', TournyPage),
                                      ('/survey.', TournyPage)],
                                     debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":

#   print __file__
#   print __name__

    main()
